<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useTodos } from "@/stores/todo";
// import { NButton, NConfigProvider, darkTheme } from 'naive-ui'
// import { useTheme } from "@/hooks/useTheme"
import DTable from "./component/DTable.vue";
import Rank from "./component/Rank/index.vue";
import Swap from "./component/Swap/index.vue";
import Activity from "./component/Activity/index.vue";
import Clever from "./component/Clever/index.vue";
import Chart from "@/components/chart/index.vue";
import Star from "@/components/star/index.vue";
import { useI18n } from "vue-i18n";
import { useTheme } from "vuetify";
import TradingView from "@/components/tradingView/tradView.vue"
import {
    onMounted,
    reactive,
    ref,
    onActivated,
    onDeactivated,
    watch,
    onBeforeMount
} from "vue";
import { useAccount } from "@/stores/account";
import CoinState from "./component/CoinState/index.vue";
import NavTitle from "./component/NavTitle/index.vue";
import Copyright from "@/components/copyright/index.vue";
import Lines from "@/components/lines/index.vue";
import CleverDeal from "./clever_deal/index.vue";
import OnChain from "@/assets/onChain.png";
import BankIcon from "@/assets/bank.png";
import CleverIcon from "@/assets/clever.png";
import { useClever } from "@/stores/clever";
import { useKline } from "@/stores/kline";
import { YShare } from "@/components/y-share/script/index";
import YFloatBtn from "@/components/y-floatbtn/index.vue"
// import { onScroll } from '@/comm/tools';
import { Bus, CHART_KLINE_SUBSCRIBE, CHART_KLINE_SUBSCRIBE_TIME, CONN_ACTIVITY_RETRY, SizeChart, CHANGE_HOME_CHART } from "@/connetion/Bus";
import html2canvas from "html2canvas";
import { useRouter } from "vue-router";
import i18n from "@/locals";
import { useLayout } from "@/stores/layout";
import { Conn } from "@/connetion/Conn";
import YTest from "@/components/y-test2/index.vue"
import { useTradingView } from "@/stores/tradingVIew";
import Loading from "@/components/chart/loading/index.vue";

let tradingView = useTradingView()
const clever = useClever();
const kline = useKline();
// const chart = ref();
const account = useAccount();
const theme = useTheme();
const router = useRouter();
const layout = useLayout();
const heightData = layout.heightData
function toggleTheme() {
    theme.global.name.value = theme.global.current.value.dark ? "light" : "dark";
}

// watch(()=>kline.map.length, (val)=>{
//     console.log("jsz kline.map", val);
// })

const changeCoin = () => {
    clever.init();
};
watch(
    () => layout.chartsHeight,
    (newVal: any, oldVal: any) => {
        // console.log('改变高度了！！！', newVal,window.innerHeight - heightData)
        if (newVal <= 0) {
            maxChart.value = true
        }
        else if (newVal < window.innerHeight - heightData) {
            layout.mediumChart = false
            maxChart.value = false
        } else {
            layout.mediumChart = true
        }
    }
);
// 组件注册（伪注册）
const componentList = {
    TradingView,
    Chart
}
onActivated(() => {
    document.body.scrollTop = 0;
});

onMounted(() => {
    // console.log("home onMounted");
    // if(!kline.curCoin){
    //     kline.changeCurCoin(kline.map[0]);
    // }
    //显示图表适应高度
    Bus.on(CHANGE_HOME_CHART, (data: any) => {
        if (layout.$state.chartsHeight < window.innerHeight - 300) {
            layout.$state.chartsHeight = window.innerHeight - 300;
        }
    });
    if (localStorage.getItem("init") == "0") {
        // setTimeout(() => {
        //     kline.changeCurCoin(kline.map[0]);
        //     Bus.emit(CHART_KLINE_SUBSCRIBE, kline.param);
        // }, 3000);
    }
    // document.body.addEventListener('scroll', onScroll);
});
onBeforeMount(() => {
    document.body.removeEventListener("scroll", ent => {
        console.log("scroll事件移除", ent);
    });
});

onActivated(() => {
    console.log("home onActivated");
    // setTimeout(() => {
    //     Bus.emit(CONN_ACTIVITY_RETRY);
    // }, 1000);
    Conn.ins.homeSubscribe(true);
});
onDeactivated(() => {
    console.log("home onDeactivated");
    // chart.value.cancelTimer();
    Conn.ins.homeSubscribe(false);
});

// const { num } = useTheme();
const { t, locale } = useI18n();

const store = useTodos();
const { filter } = storeToRefs(store);

const toggleLang = () => {
    locale.value = locale.value === "zh" ? "en" : "zh";
};

const moreClever = () => {
    // alert("clever");
};

const moreActivity = () => {
    // alert("activity");
    kline.saveLastData();
    router.push("/layout/clever");
};

async function Open() {
    const char: HTMLCanvasElement = document.body.querySelector(".chart-div")!;
    const color = char.style.background;
    char.style.background = "var(--card)";
    const canvas = await html2canvas(char);
    char.style.background = color;
    YShare.open(canvas, "Share or download chart image", "Chart");
}

let sx = 0;
let sy = 0;
let h = 0;

// const height = ref(window.innerHeight - 300);
if (layout.isMobile) {
    layout.chartsMax(window.innerHeight * 0.4);
}
else {
    layout.chartsMax(window.innerHeight - heightData);
}
const touStart = (e: any) => {
    layout.toggleIsOnEnd(true)

    const client = e.changedTouches[0]
    if (client) {
        sx = client.clientX;
        sy = client.clientY;
        // console.log('用户触摸！！！', sx, sy)
        h = layout.$state.chartsHeight;
        window.addEventListener("touchmove", touchMove);
        window.addEventListener("touchend", onUp)
    }
}
const onStart = (e: any) => {
    layout.toggleIsOnEnd(true)

    console.log(e);
    sx = e.clientX;
    sy = e.clientY;
    // console.log(sx, sy, "鼠标坐标");
    h = layout.$state.chartsHeight;
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
};
const touchMove = (e: any) => {
    // console.log('用户触摸移动中', e)
    const client = e.changedTouches[0]
    if (client) {
        layout.$state.chartsHeight = h + client.clientY - sy;
    }
    if (layout.$state.chartsHeight > (window.innerHeight - heightData)) {
        layout.$state.maxChart = true;
    } else {
        layout.$state.maxChart = false;

    }
}
const onMove = (e: any) => {
    // console.log('用户移动中', e)
    // sx = e.clientX;
    layout.$state.chartsHeight = h + e.clientY - sy;
    // console.log(layout.$state.chartsHeight, (window.innerHeight - heightData))
    if (layout.$state.chartsHeight > (window.innerHeight - heightData)) {
        layout.$state.maxChart = true;
    } else {
        layout.$state.maxChart = false;

    }
};
// 阻止默认事件
function onEnd(e: Event) {
    layout.toggleIsOnEnd(false)
}
const onUp = (e: any) => {
    window.removeEventListener("mousemove", onMove);
    window.removeEventListener("mouseup", onUp);
    window.removeEventListener("touchmove", touchMove);
    window.removeEventListener("touchend", onUp)
    Bus.emit(SizeChart);
};
let maxChart = ref(false);
// const mediumChart = ref(false)
const doms = ref<any>(null);
const curHash = ref<any>(null);
const step = [0, 240, 550];
const inScorll = ref(false)
let lastHeight = 0;
const fast = ref<any>(null);
const mediumSize = () => {
    const smartlDom = document.getElementById('smart-box')
    let cleverOne: number = 0;
    let totalH: number = 0;
    if (smartlDom) {
        cleverOne = smartlDom!.offsetHeight + 7  //单个大致高度
        totalH = cleverOne
        if (layout.mediumChart) {
            layout.$state.chartsHeight = window.innerHeight - heightData - totalH
        } else {
            layout.$state.chartsHeight = window.innerHeight - heightData
        }
    }
    // console.log('fast 高度', fast.value.offsetHeight, 'totalH', totalH)
    layout.mediumChart = !layout.mediumChart
    Bus.emit(SizeChart);
}
const toggleSize = () => {
    // console.log('当前按钮', maxChart.value)
    if (!maxChart.value) {
        lastHeight = layout.$state.chartsHeight;
        layout.$state.chartsHeight = 0;
    } else {
        layout.$state.chartsHeight = window.innerHeight - heightData;
    }
    maxChart.value = !maxChart.value
    // if (layout.$state.chartsHeight == 0) {
    //     layout.$state.chartsHeight = window.innerHeight - heightData;
    //     maxChart.value = false
    // } else {
    //     lastHeight = layout.$state.chartsHeight;
    //     layout.$state.chartsHeight = 0;
    //     maxChart.value = true

    // }
    Bus.emit(SizeChart);
};
const jump = (n: number) => {
    if (layout.$state.chartsHeight == window.innerHeight - heightData) {
        layout.$state.chartsHeight = window.innerHeight - 300;
        layout.$state.maxChart = false;
    }
    curHash.value = n;
    let num = 0;
    // if(n)
    // if (n == 1) {
    //     num = step[1];
    // } else if (n == 2) {
    //     num = step[2];
    // }
    // doms.value.scrollTop = num;
    inScorll.value = true
    const setInScorll = () => {
        setTimeout(() => {
            inScorll.value = false
        }, 1000);
    }
    if (n == 0) {
        const cleverDeal_el = document.getElementById("cleverDeal_box");
        if (cleverDeal_el) {
            cleverDeal_el.scrollIntoView({ behavior: 'smooth' })
            setInScorll()
        }
    }
    if (n == 1) {
        const swap_el = document.getElementById("swap_box");
        if (swap_el) {
            swap_el.scrollIntoView({ behavior: 'smooth' })
            setInScorll()
        }
    }
    if (n == 2) {
        const activit_el = document.getElementById("activit_box");
        if (activit_el) {
            activit_el.scrollIntoView({ behavior: 'smooth' })
            setInScorll()
        }
    }
};

const onScroll = () => {
    let n = doms.value.scrollTop;
    if (inScorll.value) return
    // console.log('滑动距离', n)
    if (n < step[1]) {
        curHash.value = 0;
    } else if (n < step[2]) {
        curHash.value = 1;
    } else {
        curHash.value = 2;
    }
};

</script>

<template>
    <div class="home-cont user-none">
        <!-- <YTest></YTest> -->
        <div class="all-top" :style="{ height: layout.chartsHeight + 'px' }">
            <CoinState></CoinState>
            <component :is="componentList[tradingView.chartsType]"></component>
            <!-- <div class="mask" >
            </div> -->
            <div class="t-loading" v-if="layout.chartsLoading">
                <Loading></Loading>
            </div>

        </div>
        <div class="all-line" @mousedown="onStart" @touchstart="touStart" @mouseup="onEnd($event)"
            @touchend="onEnd($event)"></div>

        <div class="j-fast c-title-4" ref="fast">
            <div class="j-fbtn" @click="jump(0)" :class="{ cur: curHash == 0 }">{{ i18n.global.t('message.fast.a') }}</div>
            <div class="j-fbtn" @click="jump(1)" :class="{ cur: curHash == 1 }">{{ i18n.global.t('message.fast.b') }}</div>
            <div class="j-fbtn" @click="jump(2)" :class="{ cur: curHash == 2 }">{{ i18n.global.t('message.fast.c') }}</div>
            <div class="medium" @click="mediumSize">
                <span class="icon" v-if="layout.mediumChart">
                    <VIcon>mdi mdi-apple-keyboard-control</VIcon>
                </span>
                <span class="icon" v-else>
                    <VIcon>mdi mdi-minus</VIcon>
                </span>
            </div>
            <div class="maxmin" @click="toggleSize">
                <span class="iconfont icon-actualsize" v-if="maxChart" :title="$t('message.fast.d')"></span>
                <span class="iconfont icon-actualsize1" v-else :title="$t('message.fast.e')"></span>
            </div>
        </div>
        <div class="all-bottom" ref="doms" @scroll="onScroll">
            <CleverDeal></CleverDeal>
            <Swap></Swap>
            <Rank></Rank>
            <Activity></Activity>
            <div style="height: 20px;"></div>
        </div>
    </div>
</template>

<style lang="less" scoped>
.j-fast {
    margin: 4px 20px;
    padding-bottom: 4px;
    // border-bottom: solid 1px var(--border);
    display: flex;
    gap: 10px;

    .j-fbtn {
        padding-bottom: 4px;
        color: #b1b6c6;

        &:hover {
            color: var(--main);
        }

        &.cur {
            color: var(--main);
            border-bottom: solid 1px var(--main);
        }
    }

    .medium {
        width: 30px;
        height: 20px;
        margin-left: auto;

        .icon {
            color: #9a9fad;

            &:hover {
                color: var(--main);
            }
        }
    }

    .maxmin {
        // margin-left: auto;
        width: 20px;
        height: 20px;
        // background: rgba(0, 0, 0, 0.3);
        display: flex;
        justify-content: center;
        align-items: center;
        color: #b1b6c6;

        .iconfont {
            font-size: 20px;
        }

        .icon-actualsize1 {
            font-size: 22px;
        }

        &:hover {
            color: var(--main);
        }
    }
}

.mask {
    position: absolute;
    // top: 0;
    // left: 0;
    height: 100%
}

.t-loading {
    width: 100%;
    height: calc(100% - 60px);
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
}

.ts-3 {
    color: rgb(5, 139, 95);
}

.title-more {
    display: flex;
    align-items: center;

    .mdi {
        font-size: 20px;
        margin-right: 10px;
    }
}

// .b-img {
//     margin-left: 4px;
//     display: flex;
//     justify-content: space-between;
//     align-items: flex-end;
//     width: 18px;
//     height: 16px;

//     .r-line {
//         height: 100%;
//         width: 23.2%;
//         background: #f6475d;
//         animation: glow 1.8s linear;
//         animation-iteration-count: infinite;
//     }

//     .line-1 {
//         animation-delay: 0.2s;
//     }

//     .line-2 {
//         animation-delay: 0.6s;
//     }

//     .line-3 {
//         animation-delay: 0.8s;
//     }
// }

// @keyframes glow {
//     0% {
//         height: 20%;
//     }

//     40% {
//         height: 100%;
//     }

//     60% {
//         height: 100%;
//     }

//     100% {
//         height: 20%;
//     }
// }
.home-cont {
    position: relative;
    padding-bottom: 1px;
    height: 100%;
    overflow-y: auto;
    // border: solid 2px red;
    display: flex;
    flex-direction: column;

    .all-top {
        height: 0;
        box-sizing: border-box;
        overflow-y: hidden;
        display: flex;
        flex-direction: column;
    }

    .all-line {
        margin-top: 2px;
        height: 6px;
        background: rgba(0, 0, 0, 0.1);
        cursor: ns-resize;

        &:hover {
            border-top: dotted 1px #f0f0f0;
        }
    }

    .all-bottom {
        flex: 1;
        height: 0;
        overflow: auto;
        scroll-behavior: smooth;
    }

    .share {
        width: 59px;
        height: 42px;
        background: #2f363c;
        border-radius: 4px;
        color: var(--sub);
        font-size: 14px;
        position: absolute;
        top: 30px;
        right: 50px;
        transition: 50ms ease all;

        &:active {
            scale: 0.95;
        }
    }
}

.rows {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    justify-content: space-between;
    background: rgba(0, 0, 0, 0.3);
    padding: 30px;

    .cols {
        flex: 1;
        min-width: 200px;
        // max-width: 400px;
        border: solid 1px #9b9b9b7c;
        height: 200px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 40px;
        color: #f0f0f057;
    }
}
</style>
